//
//  ReadingPageViewController.m
//  ddj
//
//  Created by linqc on 17/7/1.
//  Copyright © 2017年 linqc. All rights reserved.
//

#import "ContentPageViewController.h"
#import "Common.h"
#import "MyWebView.h"
#import "DictPageViewPlugin.h"


@interface ContentPageViewController ()<WKNavigationDelegate> {
    UILabel *titleLabel_;
    NSDictionary* json_;
    
    MyWebView* contentWebView_;

    NSMutableArray* _webImages;
    CGSize _webContentSize;
    CGPoint _webImageOffset;
    int64_t _platformViewId;
    int _tabIndex;
}
@end

@implementation ContentPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createWebView];
    [self createTitleView];
    [contentWebView_ loadHTMLString:@"" baseURL:NULL];
}

-(void)setPlatformViewId:(int64_t)viewId andTabIndex:(int)tabIndex{
    _platformViewId = viewId;
    _tabIndex = tabIndex;
    if (contentWebView_) [contentWebView_ setPlatformViewId:_platformViewId andTabIndex:_tabIndex];
}

- (id)initWithJson:(NSDictionary *)json {
    self = [super init];
    json_ = json;
    if (self->titleLabel_) {
        self->titleLabel_.text = [json valueForKey:@"name"];
    }
    return self;
}

- (void)loadUrl:(NSString *)urlPath {
    if ([urlPath rangeOfString:@"http://"].location == 0 ||
        [urlPath rangeOfString:@"https://"].location == 0) {
        [self->contentWebView_ loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlPath]]];
        return;
    }
    NSString* basePath = [urlPath stringByDeletingLastPathComponent];
    NSURL* url = [NSURL fileURLWithPath:urlPath];
    NSURL* baseUrl = [NSURL fileURLWithPath:basePath];
    [self->contentWebView_ loadFileURL:url allowingReadAccessToURL:baseUrl];
}

-(void)createTitleView {
    if (self->titleLabel_) {
        [self->titleLabel_ removeFromSuperview];
    }
    
    self->titleLabel_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    [self.view addSubview:self->titleLabel_];
    titleLabel_.backgroundColor = [UIColor colorWithRed:0xc1/255.0 green:0xc1/255.0 blue:0xc1/255.0 alpha:1];
    [Common addLayoutConstraintsWithParentView:self.view contentView:titleLabel_ left:0 top:0 right:0 bottom:INVLIAD_CONSTRAINT_VALUE width:INVLIAD_CONSTRAINT_VALUE height:44];
    titleLabel_.textAlignment = NSTextAlignmentCenter;
    
    if (json_) {
        titleLabel_.text = [json_ valueForKey:@"name"];
    }
}


-(void)createWebView {
    if (self->contentWebView_) {
        [self->contentWebView_ removeFromSuperview];
    }
    
    self->contentWebView_ = [[MyWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
   // [scrollView_ addSubview:self->contentWebView_];
    [self.view addSubview:self->contentWebView_];
    self->contentWebView_.translatesAutoresizingMaskIntoConstraints = NO;
    contentWebView_.opaque = NO;
//    contentWebView_.backgroundColor = [UIColor clearColor];
    contentWebView_.backgroundColor = [UIColor colorWithRed:0xdd/255.0 green:0xdd/255.0 blue:0xdd/255.0 alpha:1];
    self->contentWebView_.delegateLink = self;
    [Common addLayoutConstraintsWithParentView:self.view contentView:contentWebView_ left:0 top:44 right:0 bottom:0 width:INVLIAD_CONSTRAINT_VALUE height:INVLIAD_CONSTRAINT_VALUE];
    [contentWebView_ setPlatformViewId:_platformViewId  andTabIndex:_tabIndex];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

-(void)takePhoto {
    if (!_webImages) _webImages = [[NSMutableArray alloc] init];
    [_webImages removeAllObjects];

    _webImageOffset = contentWebView_.scrollView.contentOffset;
    [contentWebView_.scrollView setContentOffset:CGPointMake(0, 0)];
    _webContentSize = contentWebView_.scrollView.contentSize;

    __weak __typeof__(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakSelf) [weakSelf drawCurrentImage];
    });
}


-(void)drawCurrentImage {
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGSize boundsSize = self->contentWebView_.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize contentSize = _webContentSize;
    CGFloat contentHeight = contentSize.height;
    
    CGPoint offset = self->contentWebView_.scrollView.contentOffset;
    
    CGSize drawSize = boundsSize;
    BOOL isEnd = contentHeight - offset.y <= boundsHeight;
    
    UIGraphicsBeginImageContextWithOptions(drawSize, NO, 0.0);
    [self->contentWebView_.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [_webImages addObject:image];
    
    CGFloat offsetY = self->contentWebView_.scrollView.contentOffset.y;
    [self->contentWebView_.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
    
    if (isEnd) {
        CGSize imageSize = CGSizeMake(contentSize.width * scale,
                                      contentSize.height * scale);
        UIGraphicsBeginImageContext(imageSize);
        [_webImages enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
            [image drawInRect:CGRectMake(0,
                                         scale * boundsHeight * idx,
                                         scale * boundsWidth,
                                         scale * boundsHeight)];
        }];
        UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSData *imagedata = UIImagePNGRepresentation(fullImage);

        NSString* path = [Common getWrittenFilePath:@"小素典截圖.png"];
        [imagedata writeToFile:path atomically:YES];

        FlutterMethodChannel* channel = [DictPageViewPlugin getChannel];
        if (channel) {
            NSDictionary* args = @{
                    @"id": [NSNumber numberWithInt:_platformViewId]
            };
            [channel invokeMethod:@"tokePhotoDone" arguments:[Common objectToJson:args]];
        }

        [Common shareFile:path inVc:self];

        [self->contentWebView_.scrollView setContentOffset:_webImageOffset];
    } else {
        __weak __typeof__(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf) [weakSelf drawCurrentImage];
        });
    }
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // web網頁，且不是我維護的，不處理
    // 解決問題：在訪問某些網頁時，有些網頁指定refers，會導致加載失敗
    // 故不作通信處理
    NSString* type = [json_ objectForKey:@"type"];
    NSString* url = navigationAction.request.URL.absoluteString;

    NSLog(@"..decidePolicyForNavigationAction:%@", url);

    if ([@"web" isEqualToString: type] && ![url containsString:@"maiyuren.com"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }

    FlutterMethodChannel* channel = [DictPageViewPlugin getChannel];
    if (channel && url) {
        NSDictionary* args = @{
                @"id": [NSNumber numberWithInt:_platformViewId],
                @"tabIndex": [NSNumber numberWithInt:_tabIndex],
                @"url": url
        };
        [channel invokeMethod:@"shouldOverrideUrlLoading" arguments:[Common objectToJson:args] result:^(id  _Nullable result){
            NSNumber* boolNum = result;
            if (decisionHandler) decisionHandler(boolNum && [boolNum boolValue] ? WKNavigationActionPolicyCancel : WKNavigationActionPolicyAllow);
        }];
        return;
    }

    
    decisionHandler(WKNavigationActionPolicyAllow);
}


// <5>页面加载完成时使用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

}

@end
